package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.java4less.rchart.Chart;
import com.java4less.rchart.ChartLoader;
import com.java4less.rchart.android.ChartPanel;
import com.java4less.rchart.gc.android.ChartAndroidImage;
import com.yxt.common.sys.CommConstant;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;  
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class SoilStationChartActivity extends Activity {
	
	private Map<String,String> station = new HashMap<String,String>();
	private StringBuffer xalias = new StringBuffer();
	private StringBuffer xvalue1 = new StringBuffer();
	private StringBuffer xvalue2 = new StringBuffer();
	private StringBuffer xvalue3 = new StringBuffer();
	private ChartLoader cha = new ChartLoader();
	private ChartPanel chartPanel;
	private String code;
	private ProgressDialog dialog;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		setContentView(R.layout.soil_chart);
		ActivityStackControlUtil.add(this);
		Button btnBackHome = (Button)findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		Button btnForward = (Button)findViewById(R.id.btnForward);
		btnForward.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.putExtra("code", code);
				intent.setClass(getApplicationContext(), SoilStationDataActivity.class);
				startActivity(intent);
			}
		});
		initComponent();	
	}
	
	private void initComponent(){
		dialog = new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler(){
			// 处理来自线程的消息,并将线程中的数据设置入listview
			public void handleMessage(Message msg)	{
				if (msg.what == 1)	{				
					ChartAndroidImage.assets = getAssets();
					String chartfile = "soilchart.txt";
					chartPanel = new ChartPanel(getApplicationContext());
					try {
						chartPanel.setChart(loadFromAsset(chartfile));
					} catch (Exception e) {
						Log.e(ChartPanel.TAG, "Could not lod chart from file.", e);
					}
					LinearLayout layout = (LinearLayout)findViewById(R.id.pnlMiddle);
					layout.addView(chartPanel);
					
					TextView lblTitle = (TextView)findViewById(R.id.lblTitle);
					lblTitle.setText(station.get("name"));
					dialog.cancel();	
				}
			}
		};
		
		new Thread(){
			public void run(){
				Looper.prepare();
				downloadSoilList();
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m);	// 给handle发送的消息
				Looper.loop();
			};

		}.start();
	}	

	private void downloadSoilList() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new SoilChartHandler());
		} catch (Exception e) {
			dialog.cancel();
			throw new InternetException("");
		}		
	}
	
	private InputStream getInputStream() throws IOException{
		Intent intent = getIntent();		
		code = intent.getStringExtra("code");
		String server = CommConstant.Sever.SHANG_SERVER;
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"soilchart.xml");
		} else {
			URL url = new URL(server + "Soil/SoilHistory.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE+"&stacode=" + code);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}
	
	private class SoilChartHandler extends DefaultHandler {
		private String day = " ";
		private boolean start = false;
		
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("station".equals(localName)) {
				for (int i = 0; i < attrs.getLength(); i++) {
					station.put(attrs.getLocalName(i), attrs.getValue(i));
				}
			}else if ("soil".equals(localName)) {
				String time = attrs.getValue("time").substring(5,13);
				xvalue1.append(attrs.getValue("slm10") + "|");
				xvalue2.append(attrs.getValue("slm20") + "|");
				xvalue3.append(attrs.getValue("slm40") + "|");
				if (!time.startsWith(day)) {
					day = time.substring(0,5);
					start = true;
				}
				xalias.append(Integer.parseInt(time.substring(6)));
				if (start) {
					xalias.append(" " + Integer.parseInt(day.substring(3, 5)) + "/" + Integer.parseInt(day.substring(0, 2)) + " ");
				}
				xalias.append("|");
				start = false;
			} else if ("message".equals(localName)) {
				dialog.cancel();
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}
	
	public Chart loadFromAsset(String name) throws IOException {
		InputStream is = getAssets().open(name);
		cha.loadFromFile(is, true);
		if (xalias.length() == 0) {
			cha.setParameter("XAXIS_LABELS", "");
			cha.setParameter("SERIE_DATA_1", "");
			cha.setParameter("SERIE_DATA_2", "");
			cha.setParameter("SERIE_DATA_3", "");
		} else {
			cha.setParameter("XAXIS_LABELS", xalias.substring(0,xalias.length()-1));
			cha.setParameter("SERIE_DATA_1", xvalue1.substring(0,xvalue1.length()-1));
			cha.setParameter("SERIE_DATA_2", xvalue2.substring(0,xvalue2.length()-1));
			cha.setParameter("SERIE_DATA_3", xvalue3.substring(0,xvalue3.length()-1));
		}

		Chart c = cha.build(false, false);
		c.setWidth(LayoutParams.FILL_PARENT);
		c.setHeight(LayoutParams.FILL_PARENT);
		return c;
	}
	
	protected void onDestroy() {     
        super.onDestroy();
        ActivityStackControlUtil.remove(this);
	}
}